package com.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.dto.PageDTO;
import com.ydd.dto.RoleDTO;
import com.ydd.entity.SysRole;
import com.ydd.entity.SysRoleMenu;
import com.ydd.mapper.SysMenuMapper;
import com.ydd.mapper.SysRoleMapper;
import com.ydd.mapper.SysRoleMenuMapper;
import com.ydd.result.Result;
import com.ydd.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydd.vo.MenuList;
import com.ydd.vo.PageVO;
import com.ydd.vo.RoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-05-15
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysRoleMenuServiceImpl roleMenuService;
    @Autowired
    private SysMenuServiceImpl menuService;
    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public Result roleList(PageDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getLimit());
        Page<SysRole> roleList = roleMapper.roleList(dto);
        List<RoleVO> data = new ArrayList<>();
        roleList.forEach(sysRole -> {
            RoleVO vo = new RoleVO();
            BeanUtils.copyProperties(sysRole, vo);
            List<SysRoleMenu> roleMenus = roleMenuMapper.getMenuIds(sysRole.getId());
            List<Integer> collect = roleMenus.stream()
                    .map(sysRoleMenu -> Integer.valueOf(sysRoleMenu.getMenuId()))
                    .collect(Collectors.toList());
            vo.setMenuids(collect);
            data.add(vo);
        });
        PageVO pageVO = PageVO.builder()
                .count(roleList.getTotal())
                .pageSize(dto.getLimit())
                .currentPage(dto.getPage())
                .data(data).build();
        return Result.success(pageVO);
    }


    @Transactional
    @Override
    public Result updateRole(RoleDTO dto) {
        if (dto.getId() == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);

        }
        SysRole role = new SysRole();
        BeanUtils.copyProperties(dto, role);
        this.updateById(role);
        List<String> menuids = dto.getMenuids();
        //取出旧的权限id列表删除
        List<SysRoleMenu> menuIds = roleMenuMapper.getMenuIds(dto.getId());
        List<String> stream = menuIds.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        if (stream.size() != 0 && stream != null) {
            roleMenuMapper.delByIds(stream, dto.getId());
        }
        List<SysRoleMenu> roleMenuArrayList = new ArrayList<>();
        if (menuids == null || menuids.size() == 0) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        menuids.forEach(S -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(dto.getId());
            sysRoleMenu.setMenuId(S);
            roleMenuArrayList.add(sysRoleMenu);
        });
        roleMenuService.saveBatch(roleMenuArrayList);

        return Result.success();
    }

    @Override
    public Result rowInfo(String id) {

        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getId, id);
        SysRole one = this.getOne(wrapper);
        RoleVO vo = new RoleVO();
        List<MenuList> authList = menuMapper.getMenuByRoleId(id, 0);
        if (authList != null && authList.size() != 0) {
            children(authList, id);
        }
        vo.setAuthList(authList);
        BeanUtils.copyProperties(one, vo);
        return Result.success(vo);
    }

    @Override
    public Result allData() {
        LambdaQueryWrapper<SysRole> wp = new LambdaQueryWrapper<>();

        wp.eq(SysRole::getDelFlag, 0);
        List<SysRole> list = this.list(wp);
        return Result.success(list);
    }

    @Transactional
    @Override
    public Result addRole(RoleDTO dto) {
        if (dto == null || dto.getName() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);

        }
        LambdaQueryWrapper<SysRole> wq = new LambdaQueryWrapper<>();
        wq.eq(SysRole::getName, dto.getName());
        SysRole role = this.getOne(wq);
        if (role != null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(dto, sysRole);
        this.save(sysRole);
        if (dto.getMenuids() != null || dto.getMenuids().size() != 0) {
            List<String> list = dto.getMenuids();
            list.forEach(s -> {
                SysRoleMenu menu = new SysRoleMenu();
                menu.setMenuId(s);
                menu.setRoleId(sysRole.getId());
                roleMenuService.save(menu);
            });

        }

        return Result.success();
    }

    @Transactional
    @Override
    public Result delRole(String id) {
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        SysRole role = new SysRole();
        role.setId(id);
        this.removeById(role);
        QueryWrapper<SysRoleMenu> qw = new QueryWrapper<>();
        qw.eq("role_id", id);
        roleMenuService.remove(qw);
        return Result.success();
    }

    /**
     * 设置子菜单权限
     *
     * @param
     * @return
     */
    public void children(List<MenuList> authList, String id) {
        authList.forEach(menuList -> {
            List<MenuList> children = menuMapper.getMenuByRoleId(id, menuList.getId());
            if (children.size() == 0) {
                return;
            }
            menuList.setChildren(children);
            children(children, id);
        });
    }
}